package com.zx.map.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.utils.MyBeanUtils;
import com.zx.map.utils.SUConstants;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import com.zx.map.dao.OrdLogDao;
import com.zx.map.dao.mapper.UserMapper;
import com.zx.map.dao.model.OrdLog;
import com.zx.map.dao.model.OrdLogExample;
import com.zx.map.service.AgentInfoService;
import com.zx.map.service.OrdLogService;
import com.zx.map.service.UserService;
import com.zx.map.service.domain.OrdLogDomain;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.OrdLogModel;
import com.zx.platform.utils.PmpUtils;

/**
 * 平台查询：查询代理发展的用户（包含自己）的交易
 */
@Component("ordLogService")
public class OrdLogServiceImpl implements OrdLogService {
	private  Logger log = Logger.getLogger(OrdLogServiceImpl.class);
	@Autowired
	private OrdLogDao ordLogDao;
	@Autowired
	private AgentInfoService agentInfoService;
	@Autowired
	private MerchantInfoService merchantInfoService;
	@Autowired
	private UserService userService;

	/**
	 * 得到所有数据列表
	 */
	public List getAllList() throws DataAccessException {
		List<OrdLog> list = ordLogDao.getListByExample(null);
		List<OrdLogModel> modelList = new ArrayList<OrdLogModel>();
		for (OrdLog o : list) {
			OrdLogModel temp = new OrdLogModel();
			BeanUtils.copyProperties(o, temp);
			modelList.add(temp);
		}
		return modelList;

	}

	/**
	 * 根据单Key查找Model
	 */
	public OrdLogModel getModelByKey(String key) throws DataAccessException {
		OrdLog o = ordLogDao.selectByPrimaryKey(key);
		OrdLogModel model = new OrdLogModel();
		BeanUtils.copyProperties(o, model);
		return model;
	}

	/**
	 * 根据单Key查找Model 并增加行锁
	 */
	public OrdLogModel selectByPrimaryKeyAndLineLock(String key) throws DataAccessException {
		OrdLog o = ordLogDao.selectByPrimaryKeyAndLineLock(key);
		OrdLogModel model = new OrdLogModel();
		BeanUtils.copyProperties(o, model);
		return model;
	}


	/**
	 * 订单查询条件获取交易信息
	 *
	 * @param curAgentInfoModel
	 * @param ordLogDomain
	 * @return
	 * @throws DataAccessException
	 */
	@Override
	public List<OrdLogModel> getListByOrdLogDomain(AgentInfoModel curAgentInfoModel, OrdLogDomain ordLogDomain) throws DataAccessException {
		OrdLogExample example = initOrdLogExample(curAgentInfoModel, ordLogDomain);
		List<OrdLog> list = ordLogDao.getListByExample(example);
		List<OrdLogModel> modelList = MyBeanUtils.map(list, OrdLogModel.class);
		return modelList;
	}

	/**
	 * 根据Model查找列表
	 */
	public List<OrdLogModel> getListByModel(OrdLogModel model) throws DataAccessException {
		OrdLogExample example = new OrdLogExample();
		OrdLogExample.Criteria criteria = example.createCriteria();
		AgentInfoModel agentInfoModel = new AgentInfoModel();
		if (StringUtils.isNotBlank(model.getAgentId())) {
			AgentInfoModel pAgent = agentInfoService.getModelByKey(model.getAgentId());
			agentInfoModel.setAgentId(pAgent.getAgentId());
			agentInfoModel.setAgentLevel(pAgent.getAgentLevel());
		}

		List<String> values = agentInfoService.queryDownAgentIdList(agentInfoModel);
		if (values == null || values.size() == 0) {
			values = new ArrayList();
			values.add("-1");
		}
		criteria.andAgentIdIn(values);

		if (StringUtils.isNotBlank(model.getMerchantId())) {
			criteria.andMerchantIdEqualTo(model.getMerchantId());
		}
		if (StringUtils.isNotBlank(model.getPaymentTime())) {
			criteria.andPaymentTimeEqualTo(model.getPaymentTime());
		}
		if (StringUtils.isNotBlank(model.getOrdId())) {
			criteria.andOrdIdEqualTo(model.getOrdId());
		}
		if (null != model.getPaymentAmt()) {
			criteria.andPaymentAmtEqualTo(model.getPaymentAmt());
		}
		if (StringUtils.isNotBlank(model.getPaymentType())) {
			criteria.andPaymentTypeEqualTo(model.getPaymentType());
		}
		List<OrdLog> list = ordLogDao.getListByExample(example);
		List<OrdLogModel> modelList = new ArrayList<OrdLogModel>();
		for (OrdLog o : list) {
			OrdLogModel temp = new OrdLogModel();
			BeanUtils.copyProperties(o, temp);
			modelList.add(temp);
		}
		return modelList;
	}

	/**
	 * 单标查询
	 * @param ordLog
	 * @return
	 */
	@Override
	public List<OrdLog> getListByRecord(OrdLog ordLog) {
		OrdLogExample example = new OrdLogExample();
		OrdLogExample.Criteria criteria = example.createCriteria();
		//商户账号
		if (StringUtils.isNotBlank(ordLog.getMerSysAccount())) {
			criteria.andMerSysAccountLike("%" + ordLog.getMerSysAccount() + "%");
		}
		//代理商编号
		if (StringUtils.isNotBlank(ordLog.getAgentSysAccount())) {
			criteria.andAgentSysAccountLike("%" + ordLog.getAgentSysAccount() + "%");
		}
		//交易状态
		if (StringUtils.isNotBlank(ordLog.getTransStatus())) {
			criteria.andTransStatusEqualTo(ordLog.getTransStatus());
		}

		if (StringUtils.isNotBlank(ordLog.getTransType())) {//交易类型查询
			criteria.andTransTypeEqualTo(ordLog.getTransType());
		}
		if (StringUtils.isNotBlank(ordLog.getOrdId())) {
			criteria.andOrdIdLike("%" + ordLog.getOrdId() + "%");
		}
		//终端编号
		if (StringUtils.isNotBlank(ordLog.getTerminalId())) {
			criteria.andTerminalIdLike('%' + ordLog.getTerminalId() + '%');
		}
		if (StringUtils.isNotBlank(ordLog.getMerchantId())) {
			criteria.andMerchantIdEqualTo(ordLog.getMerchantId());
		}
		if (StringUtils.isNotBlank(ordLog.getPaymentTime())) {
			criteria.andPaymentTimeEqualTo(ordLog.getPaymentTime());
		}
		if (StringUtils.isNotBlank(ordLog.getPaymentType())) {
			criteria.andPaymentTypeEqualTo(ordLog.getPaymentType());
		}

		if (ordLog.getCreateDate()!=null) {
			criteria.andCreateDateGreaterThanOrEqualTo(ordLog.getCreateDate());
		}
		List<OrdLog> list = ordLogDao.getListByExample(example);
		return list;
	}

	/**
	 * 新增
	 */
	public String add(OrdLogModel model) throws DataAccessException {
		OrdLog temp = new OrdLog();
		BeanUtils.copyProperties(model, temp);
		String key = ordLogDao.add(temp);
		return key;
	}

	/**
	 * 修改
	 */
	public String update(OrdLogModel model) throws DataAccessException {
		OrdLog temp = new OrdLog();
		BeanUtils.copyProperties(model, temp);
		ordLogDao.update(temp);
		return model.getOrdId();
	}

	/**
	 * 删除
	 */
	public void delete(OrdLogModel model) throws DataAccessException {
		OrdLog temp = new OrdLog();
		BeanUtils.copyProperties(model, temp);
		ordLogDao.delete(temp);
	}

	/**
	 * 分页查询下级代理商交易
	 *
	 * @param domain
	 * @return
	 * @throws DataAccessException
	 */
	@Override
	public Map getPageByDomain(AgentInfoModel curAgentInfoModel, OrdLogDomain domain)
			throws DataAccessException {

		Map<String, Object> map = new HashMap<String, Object>();
		OrdLogExample example = initOrdLogExample(curAgentInfoModel, domain);

		int pageBegin = (domain.getPageNum() - 1) * domain.getPageSize();
		List<OrdLog> list = ordLogDao.getPageByExample(domain.getPageSize(), pageBegin, example);
		List<OrdLogModel> menuModelList = new ArrayList<OrdLogModel>();
		menuModelList = MyBeanUtils.map(list, OrdLogModel.class);
		int count = ordLogDao.countByExample(example);
		//add by wenjw 2016.9.20
		//交易汇总查询：当前订单总记录数：x笔，订单总额：x元。
		double paymentAmt = ordLogDao.getPaymentAmt(example);
		map.put("paymentAmt", paymentAmt);
		map.put("count", count);
		map.put("list", menuModelList);
		return map;
	}

	private OrdLogExample initOrdLogExample(AgentInfoModel curAgentInfoModel, OrdLogDomain domain) {
		if (curAgentInfoModel!=null){
			curAgentInfoModel.setHasSelf(true);
		}
		AgentInfoModel agentInfoModel = new AgentInfoModel();
		agentInfoModel.setAgentName(domain.getAgentName());
		agentInfoModel.setParentAgentId(domain.getParentAgentId());
		//商户条件过滤
		MerchantInfoModel merchantInfoModel = new MerchantInfoModel();
		merchantInfoModel.setMerchantName(domain.getMerchantName());
		//符合商户条件id列表
		List<String> merchantIdList = merchantInfoService.queryListMerchantIdByAgentInfo(curAgentInfoModel,merchantInfoModel);
		//代理商下级id列表
		List<String> agentIdList = agentInfoService.queryDownAgentIdList(curAgentInfoModel,agentInfoModel);

		OrdLogExample example = new OrdLogExample();
		OrdLogExample.Criteria criteria = example.createCriteria();
		if (agentIdList == null || agentIdList.isEmpty()) {
			agentIdList.add("-1");
			log.debug("下级代理空");
		}
		log.debug("下级代理长度"+agentIdList.size()+" "+agentIdList.toString());
		//代理商条件过滤
		criteria.andAgentIdIn(agentIdList);

		//商户条件过滤
		if (merchantIdList == null || merchantIdList.isEmpty()) {
			merchantIdList.add("-1");
			log.debug("商户空");
		}
		criteria.andMerchantIdIn(merchantIdList);

		if (StringUtils.isNotBlank(domain.getBeginDate())) {
			criteria.andCreateDateBetween(PmpUtils.strToDate(domain.getBeginDate(), "yyyy-MM-dd"),
					PmpUtils.addDate(PmpUtils.strToDate(domain.getEndDate(), "yyyy-MM-dd"), 1));
		}
		//商户账号
		if (StringUtils.isNotBlank(domain.getMerSysAccount())) {
			criteria.andMerSysAccountLike("%" + domain.getMerSysAccount() + "%");
		}
		//代理商编号
		if (StringUtils.isNotBlank(domain.getAgentSysAccount())) {
			criteria.andAgentSysAccountLike("%" + domain.getAgentSysAccount() + "%");
		}
		//交易状态
		if (StringUtils.isNotBlank(domain.getTransStatus())) {
			criteria.andTransStatusEqualTo(domain.getTransStatus());
		}

		if (StringUtils.isNotBlank(domain.getTransType())) {//交易类型查询
			criteria.andTransTypeEqualTo(domain.getTransType());
		}
		if (StringUtils.isNotBlank(domain.getOrdId())) {
			criteria.andOrdIdLike("%" + domain.getOrdId() + "%");
		}
		//终端编号
		if (StringUtils.isNotBlank(domain.getTerminalId())) {
			criteria.andTerminalIdLike('%' + domain.getTerminalId() + '%');
		}
		if (StringUtils.isNotBlank(domain.getMerchantId())) {
			criteria.andMerchantIdEqualTo(domain.getMerchantId());
		}
		if (StringUtils.isNotBlank(domain.getPaymentTime())) {
			criteria.andPaymentTimeEqualTo(domain.getPaymentTime());
		}
		if (StringUtils.isNotBlank(domain.getOrdId())) {
			criteria.andOrdIdEqualTo(domain.getOrdId());
		}
		if (domain.getPaymentAmt() != null) {
			criteria.andPaymentAmtBetween(domain.getPaymentAmt() - 0.01, domain.getPaymentAmt() + 0.01);
		}

		//排序add by wenjw 2015.6.2
		example.setOrderByClause("create_Date desc");
		return example;
	}

	/**
	 * 客戶端获取当日订单
	 * @param merchantId
	 * @param transStatus
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public Map<String, Object> getorderList(Map<String, Object> condition) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		OrdLogExample example = new OrdLogExample();
		OrdLogExample.Criteria criteria = example.createCriteria();
		criteria.andMerchantIdEqualTo((String)condition.get("merchantId"));
		String transStatus = condition.containsKey("transStatus") ? (String)condition.get("transStatus")  : SUConstants.TRANS_STATUS_S;
		criteria.andTransStatusEqualTo(transStatus);
		//处理时间：开始时间和默认时间都为空则设置为当天时间
		String beginDate = condition.containsKey("beginDate") ? (String)condition.get("beginDate") : "";
		String endDate = condition.containsKey("endDate") ? (String)condition.get("endDate") : "";
		
		if (StringUtils.isBlank(beginDate) && StringUtils.isBlank(endDate)) {
			throw new RuntimeException("请选择时间!");
			
		}else{
			int days = (int) ((PmpUtils.addDate(PmpUtils.strToDate(endDate, "yyyy-MM-dd"), 1).getTime() - PmpUtils.strToDate(beginDate, "yyyy-MM-dd").getTime()) / (1000 * 24 * 60 * 60));
			if(days > 90) {
				throw new  RuntimeException("时间不能查过90天!");
			}else {
				criteria.andCreateDateBetween(PmpUtils.strToDate(beginDate, "yyyy-MM-dd"),
				PmpUtils.addDate(PmpUtils.strToDate(endDate, "yyyy-MM-dd"), 1));
			}
			
		}
		
//		example.setOrderByClause("create_Date desc");
		
		List<Map<String, Object>> list = ordLogDao.orderAnalysis(example);
//		int count = ordLogDao.countByExample(example);

		//交易汇总查询：当前订单总记录数：x笔，订单总额：x元。
		double paymentAmt = ordLogDao.getPaymentAmt(example);
		map.put("paymentAmt", paymentAmt);
//		map.put("count", count);
		Map<String, Object> moneyMap = new HashMap<>();
		List<String> dateList = PmpUtils.getDateList(PmpUtils.strToDate(beginDate, "yyyy-MM-dd"), PmpUtils.strToDate(endDate, "yyyy-MM-dd"), "day");
		list.stream().forEach(e->{
			moneyMap.put(PmpUtils.dateToString((Date)e.get("day"), "yyyy-MM-dd"),e.get("totalMoney"));
		});
		
		List<Double> result = new ArrayList<>();
		dateList.stream().forEach(e->{
			
			if(moneyMap.containsKey(e)) {
				result.add((Double)moneyMap.get(e));
			}else {
				result.add(0.0);
			}
		});
		map.put("list", result);
		return map;
	}
	/**
	 * 获取前三个运营数据
	 * @param merchantId
	 * @return
	 */
	public Map<String, Object> getAnalysisForHistoryMonth(String merchantId){
		Map<String,Object> result = new HashMap<>();
		Map<String, Object> one = analysisByMonth(merchantId, -1);
		
		Map<String, Object> two = analysisByMonth(merchantId, -2);
		
		Map<String, Object> three = analysisByMonth(merchantId, -3);
		
		Map<String, Object> four = analysisByMonth(merchantId, -4);
		//比上月

		BigDecimal compareOne = BigDecimal.valueOf((Double) one.get("paymentAmt")).subtract(BigDecimal.valueOf((Double) two.get("paymentAmt")));
		
		one.put("compareLastMonth", compareOne);
		result.put("previousMonth", one);
		BigDecimal compareTwo = BigDecimal.valueOf((Double) two.get("paymentAmt")).subtract(BigDecimal.valueOf((Double) three.get("paymentAmt")));
		two.put("compareLastMonth", compareTwo);
		result.put("beforeTwoMonth", two);
		BigDecimal compareThree = BigDecimal.valueOf((Double) three.get("paymentAmt")).subtract(BigDecimal.valueOf((Double) four.get("paymentAmt")));
		three.put("compareLastMonth", compareThree);
		result.put("beforeThreeMonth", three);
		return result; 
		
	}
	/**
	 * 根据日期获取不同月份的运营数据
	 * @param merchantId
	 * @param range
	 * @return
	 */
	public Map<String,Object> analysisByMonth(String merchantId, int range){
		Map<String,Object> result = new HashMap<>();
		OrdLogExample example = new OrdLogExample();
		OrdLogExample.Criteria criteria = example.createCriteria();
		criteria.andTransStatusEqualTo(SUConstants.TRANS_STATUS_S);
		Map<String,String> lastMonth = PmpUtils.getRangeDate(new Date(), range);

		criteria.andMerchantIdEqualTo(merchantId);
		criteria.andCreateDateBetween(PmpUtils.strToDate(lastMonth.get("startDate"), "yyyy-MM-dd"),
				PmpUtils.addDate(PmpUtils.strToDate(lastMonth.get("endDate"), "yyyy-MM-dd"), 1));
		
		int count = ordLogDao.countByExample(example);
		double paymentAmt = ordLogDao.getPaymentAmt(example);
		result.put("date", PmpUtils.dateToString(PmpUtils.strToDate(lastMonth.get("startDate"), "yyyy-MM"), "yyyy年MM月"));
		result.put("count", count);
		result.put("paymentAmt", paymentAmt);
		return result;
		
	}
	/**
	 * 大额订单监控
	 */
	public Map getPageRisk(AgentInfoModel curAgentInfoModel, OrdLogDomain domain)
			throws DataAccessException {

		Map<String, Object> map = new HashMap<String, Object>();
		OrdLogExample ordLogExample=initOrdLogExample(curAgentInfoModel, domain);
		//实时监控系统中交易金额大于标准金额交易流水（eg：5W）
		ordLogExample.getOredCriteria().get(0).andPaymentAmtGreaterThanOrEqualTo(50000.0);

		int pageBegin = (domain.getPageNum() - 1) * domain.getPageSize();
		List<OrdLog> list = ordLogDao.getPageByExample(domain.getPageSize(), pageBegin, ordLogExample);
		List<OrdLogModel> menuModelList = new ArrayList<OrdLogModel>();
		for (OrdLog o : list) {
			OrdLogModel temp = new OrdLogModel();
			BeanUtils.copyProperties(o, temp);
			menuModelList.add(temp);
		}
		int count = ordLogDao.countByExample(ordLogExample);
		map.put("count", count);
		map.put("list", menuModelList);
		return map;
	}

	@Override
	public Map<String, Object> homePageData(String merchantId) throws DataAccessException {
		OrdLogExample example = new OrdLogExample();
		OrdLogExample.Criteria criteria = example.createCriteria();
		criteria.andMerchantIdEqualTo(merchantId);
		criteria.andTransStatusEqualTo(SUConstants.TRANS_STATUS_S);
		Date today = PmpUtils.strToDate(PmpUtils.dateToString(new Date(), "yyyy-MM-dd 00:00:00"), "yyyy-MM-dd 00:00:00");
		criteria.andCreateDateBetween(today, PmpUtils.addDate(today, 1));
		//今日营收
		double paymentAmt = ordLogDao.getPaymentAmt(example);
		//新增会员
		long newMembers = userService.countUsers(merchantId, today, PmpUtils.addDate(today, 1));
		//交易数量
		int paymentCount = ordLogDao.countByExample(example);
		//回头客:总会员数量-新增会员数量
		long allUsers = ordLogDao.getUsers(example);
		long oldMembers = allUsers - newMembers;
		
		Map<String, Object> result = new HashMap<>();
		result.put("paymentAmt", String.format("%.2f", paymentAmt));
		result.put("newMembers", newMembers);
		result.put("paymentCount", paymentCount);
		result.put("oldMembers", oldMembers);
		return result;
	}
	
	
	@Override
	public Map<String,Object> groupbyType(Map<String, Object> params) throws DataAccessException{
		OrdLogExample example = new OrdLogExample();
		OrdLogExample.Criteria criteria = example.createCriteria();
		criteria.andMerchantIdEqualTo((String)params.get("merchantId"));
		criteria.andTransStatusEqualTo(SUConstants.TRANS_STATUS_S);
		
		Date beginDate = new Date(), endDate = new Date();
		Map<String, Date> dates = PmpUtils.translateDate(params);
		if(!dates.isEmpty()) {
			beginDate = dates.get("beginDate");
			endDate = dates.get("endDate"); 
		}else {
			beginDate = PmpUtils.getYesterday(new Date(), true);
			endDate = PmpUtils.addDate(beginDate, 1);
		}
		criteria.andCreateDateBetween(beginDate, endDate);
		
		String statisticsType = "";
		switch((String)params.get("statisticsType")) {
			case SUConstants.TRANSTYPE_TA:
				statisticsType = "ifnull(sum(payment_amt),0) - ifnull(sum(redpacket_refund),0) as data";
				break;
			case SUConstants.TRANSTYPE_TC:
				statisticsType = "ifnull(count(*),0) as data";
				break;
			case SUConstants.TRANSTYPE_TM:
				statisticsType = "ifnull(count(distinct bg_account_id),0) as data";
				break;
			case SUConstants.TRANSTYPE_TCR:
				statisticsType = "ifnull(round((sum(payment_amt) - ifnull(sum(redpacket_refund),0))/count(*),2),0) as data";
				break;
			case SUConstants.TRANSTYPE_TMR:
				statisticsType = "ifnull(round((sum(payment_amt) - ifnull(sum(redpacket_refund),0))/count(distinct bg_account_id),2),0) as data";
				break;
			default :
				break;
			
		}
		String groupbyType = "";
		
		switch((String)params.get("groupbyType")) {
		
			case SUConstants.DATE_UNIT_DAY:
				groupbyType = "concat(year(create_date), '-',month(create_date), '-',day(create_date))";
				break;
			case SUConstants.DATE_UNIT_WEEK:
				groupbyType = "FROM_DAYS(TO_DAYS(create_date) -MOD(TO_DAYS(create_date) -2, 7))";
				break;
			case SUConstants.DATE_UNIT_MONTH:
				groupbyType = "concat(year(create_date), '-',month(create_date))";
				break;
			case SUConstants.DATE_UNIT_HOUR:
				groupbyType = "hour(create_date)";
				break;
			default:
				groupbyType = "concat(year(create_date), '-',month(create_date))";
				break;
		}
		List<Map<String, Object>> result = ordLogDao.groupbyType(example,statisticsType,groupbyType);
		HashMap<String, Object> map = new HashMap<>();
		result.stream().forEach(e->{
			map.put(e.get("cycle")+"", e.get("data"));
		});
		//例：enddate=2017-10-17，SQL语句查询的是18号的00:00:00
		List<String> dateList = PmpUtils.getDateList(beginDate, PmpUtils.addDate(endDate, -1), (String)params.get("groupbyType"));
		List<Object> resultList = new ArrayList<>();

		dateList.stream().forEach(e->{
			if(map.containsKey(e)) {
				resultList.add(map.get(e));
			}else {
				resultList.add(0.0);
			}
		});
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("x", dateList);
		resultMap.put("y", resultList);
		return resultMap;
	}
	
	@Override
	public List<Map<String, Object>> priceRange(Map<String, Object> params) throws DataAccessException{
		
		List<Map<String, Object>> result = new ArrayList<>();
		for(String price : SUConstants.PRICERANGE) {
			params.put("condition", price);
			int count = this.dealPriceRange(params);
			Map<String, Object> map = new HashMap<>();
			map.put("name", price);
			map.put("value", count);
			
			result.add(map);
		}
		
		return result;
	}
	/**
	 * 根据传入的数据，分解查询条件
	 * @param param
	 * @return
	 * @throws DataAccessException
	 */
	private int dealPriceRange(Map<String, Object> params) throws DataAccessException{
		OrdLogExample example = new OrdLogExample();
		OrdLogExample.Criteria criteria = example.createCriteria();
		criteria.andMerchantIdEqualTo((String)params.get("merchantId"));
		criteria.andTransStatusEqualTo(SUConstants.TRANS_STATUS_S);
		
		Date beginDate = new Date(), endDate = new Date();
		Map<String, Date> dates = PmpUtils.translateDate(params);
		if(!dates.isEmpty()) {
			beginDate = dates.get("beginDate");
			endDate = dates.get("endDate"); 
		}else {
			beginDate = PmpUtils.getYesterday(new Date(), true);
			endDate = PmpUtils.addDate(beginDate, 1);
		}
		criteria.andCreateDateBetween(beginDate, endDate);
		String con = (String)params.get("condition");
		Pattern pattern = Pattern.compile("\\d+");
	    Matcher matcher = pattern.matcher(con);
	    Double startPrice = 0.00, endPrice = 10000000.00;
	    
	    boolean flag = true;
	    while(matcher.find()) {
	    	if(con.contains("以下")) {
		    	endPrice = Double.parseDouble((String)matcher.group());
		    	criteria.andPaymentAmtLessThanOrEqualTo(endPrice);
		    }else if(con.contains("以上")) {
		    	endPrice = Double.parseDouble((String)matcher.group());
		    	criteria.andPaymentAmtGreaterThan(endPrice);
		    }else {
		    	
	    		if(flag) {
	    			startPrice = Double.parseDouble((String)matcher.group());
	    			criteria.andPaymentAmtGreaterThan(startPrice);
	    		}else {
	    			endPrice = Double.parseDouble((String)matcher.group());
	    			criteria.andPaymentAmtLessThanOrEqualTo(endPrice);
	    		}
	    		flag = !flag;
		    }
	    }
	    
		int result = ordLogDao.countByExample(example);
		return result;
	}
	@Override
	public Map<String, Object> tradeInfo(Map<String, Object> params) throws DataAccessException{
		
		OrdLogExample example = new OrdLogExample();
		OrdLogExample.Criteria criteria = example.createCriteria();
		criteria.andMerchantIdEqualTo((String)params.get("merchantId"));
		criteria.andTransStatusEqualTo(SUConstants.TRANS_STATUS_S);
		Date beginDate = new Date(), endDate = new Date();
		Map<String, Date> dates = PmpUtils.translateDate(params);
		if(!dates.isEmpty()) {
			beginDate = dates.get("beginDate");
			endDate = dates.get("endDate"); 
		}else {
			beginDate = PmpUtils.getYesterday(new Date(), true);
			endDate = PmpUtils.addDate(beginDate, 1);
		}
		criteria.andCreateDateBetween(beginDate, endDate);
		//今日营收
		double paymentAmt = ordLogDao.getPaymentAmt(example);
		//交易数量
		int paymentCount = ordLogDao.countByExample(example);
		//笔单价
		double amtPerCount = paymentAmt == 0 || paymentCount == 0  ? 0 : paymentAmt/paymentCount;
		
		long newMembers = userService.countUsers((String)params.get("merchantId"), beginDate, endDate);
		long oldMembers = userService.countUsersBefore((String)params.get("merchantId"), beginDate);
		Map<String, Object> result = new HashMap<>();
		result.put("paymentAmt", paymentAmt);
		result.put("paymentCount", paymentCount);
		result.put("amtPerCount", String.format("%.2f", amtPerCount));
		long allMembers = newMembers + oldMembers;
		result.put("allUsers", allMembers);
		result.put("newUsers", newMembers);
		result.put("oldUsers", oldMembers);
		result.put("newUserRate", (allMembers == 0 || newMembers == 0) ? 0 : String.format("%.2f", newMembers/allMembers * 1.0));
		
		result.put("oldUserRate", (allMembers == 0 || oldMembers == 0) ? 0 : String.format("%.2f", oldMembers/allMembers * 1.0));
		return result;
	}
}
